/**
 * @summary: 页面路由 Tabs 组件
 */
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'umi';
import { Card, Tabs } from 'antd';
import { withRouter } from 'umi';
import { formatMessage } from 'umi';
import { eventTrack } from '@/utils/track';
import routers from '@/../config/sub.router.config';
import helper from '@/utils/auth/helper';
import styles from './PageRouter.less';

const { TabPane } = Tabs;

const PageRouter = ({ type, activePath, children, match, extraButton, menuMap, tabNameMapper = {}, tabBarGutter }) => {
    const route = routers[type];

    const handleChange = key => {
        let eventName;
        let pageName;
        let label;

        // 埋点
        switch (key) {
            case '/personal/portal/recruit/task':
                eventName = 'personal_portal_recruit_task_click';
                label = '我的招聘-我的招聘任务';
                break;
            case '/personal/portal/recruit/demand':
                eventName = 'personal_my_recruit_demand_click';
                label = '我的招聘-我的招聘需求';
                break;
            case '/personal/portal/recruit/candidate':
                eventName = 'personal_my_recruit_candidate_click';
                label = '我的招聘-我的候选人';
                break;
            case 'portal:/personal/portal/recruit/talentPool:interview':
                eventName = '/personal/portal/recruit/talentPool';
                label = '我的招聘-我的人才库';
                break;
            case '/personal/portal/recruit/interview':
                eventName = 'personal_my_recruit_interview_click';
                label = '我的招聘-我的面试';
                break;
            case '/personal/portal/recruit/offer':
                eventName = 'personal_my_recruit_offer_click';
                label = '我的招聘-我的offer';
                break;
            case '/office/personnelManagement/onboardAndLeave/entryManage/waitEntry':
                eventName = 'personnel_management_onboard_and_leave_entry_manage_wait_entry_click';
                pageName = 'personnel_management_onboard_and_leave';
                break;
            case '/office/personnelManagement/onboardAndLeave/entryManage/entryHistory':
                eventName = 'personnel_management_onboard_and_leave_entry_manage_entry_history_click';
                pageName = 'personnel_management_onboard_and_leave';
                break;
            default:
                break;
        }
        eventTrack({
            eventName,
            pageName,
            eventProps: {
                label
            }
        });
        history.push(key);
    };

    // 前两个map用来处理tab路由名称和主路由名称的不同
    const routeFlag = route
        .map(item => ({ ...menuMap[item.path], ...item }))
        .map(item => {
            let { name } = item;
            if (item.editName) {
                const localeAry = item.locale.split('.');
                localeAry.splice(localeAry.length - 1, 1, item.editName);
                name = formatMessage({ id: localeAry.join('.') });
            }

            if (tabNameMapper && tabNameMapper[item.tabMapperCode]) {
                name = tabNameMapper[item.tabMapperCode];
            }

            return {
                ...item,
                name
            };
        })
        // 过滤掉配置了tabMapperCode，但是没有值的菜单
        .filter(item => !item.tabMapperCode || tabNameMapper[item.tabMapperCode])
        .filter(item => helper.checkCode(item.code));
    const activeKey = route.find(item => item.path === match.path) || '';
    const content = typeof children === 'function' ? children(activeKey) : children;
    React.useEffect(() => {
        // 校验无权限的组件
        if (activeKey && !routeFlag.some(item => item.path === match.path)) {
            if (routeFlag.length === 0) {
                history.push('/');
            }
            if (routeFlag.length > 0) {
                history.push(routeFlag[0].path);
            }
        }
    }, []);
    if (!activeKey && !activePath) return content;
    return (
        <Card bordered={false} className={styles.card} bodyStyle={{ padding: '0 16px 16px' }}>
            <Tabs
                size="large"
                className={styles.tabs}
                activeKey={activePath || activeKey.path}
                onTabClick={handleChange}
                tabBarExtraContent={extraButton}
                tabBarGutter={tabBarGutter}
            >
                {/* 过滤掉没有权限的 TabPane */}
                {routeFlag.map(item => (
                    <TabPane tab={item.name} key={item.path} />
                ))}
            </Tabs>
            {content}
        </Card>
    );
};

PageRouter.propTypes = {
    // 类型，在 sub.router.config.js 中配置
    type: PropTypes.string.isRequired,
    // 选中路径
    activePath: PropTypes.string,
    // 右侧按钮
    extraButton: PropTypes.element
};

PageRouter.defaultProps = {
    activePath: '',
    extraButton: null
};

export default withRouter(
    connect(({ menu }) => ({
        menuMap: menu.breadcrumbNameMap
    }))(PageRouter)
);
